package com.example.filepersitstencetest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {

    private EditText edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edit = findViewById(R.id.edit);

        String inputTetx = load();
        if (!TextUtils.isEmpty(inputTetx)) { // 当传入的字符串等于null或者等于空字符串的时候，这个方法都会返回true
            edit.setText(inputTetx);
            edit.setSelection(inputTetx.length()); // 将输入的光标移动到文本的末尾位置以便继续输入
            Toast.makeText(this, "Restoring succeeded", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 启动活动的时候读取文件中的数据
     * @return
     */
    private String load() {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {
            in = openFileInput("data");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     * 当活动销毁的时候将EditText中的数据保存到文件中
     */
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        String inputText = edit.getText().toString();
//        save(inputText);
//    }
//
//
//    private void save(String inputText) {
//        FileOutputStream out = null;
//        BufferedWriter writer = null;
//        try {
//            out = openFileOutput("data", MODE_PRIVATE);
//            writer = new BufferedWriter(new OutputStreamWriter(out));
//            writer.write(inputText);
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//
//                try {
//                    if (writer != null) {
//                        writer.close();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//        }
//
//    }
}
